package link_list;

import link_list.node.SinglyListNode;

/**
 * 链表中的部分反转
 */

public class LinkedListPartialInversionOld {

    public static void main(String[] args) {
        SinglyListNode first = new SinglyListNode(3);
        first.next=new SinglyListNode(2);
        first.next.next=new SinglyListNode(1);
        first.next.next.next=new SinglyListNode(5);
        first.next.next.next.next=new SinglyListNode(8);
        first.next.next.next.next.next=new SinglyListNode(7);
        first.next.next.next.next.next.next=new SinglyListNode(9);
        SinglyListNode result = reverseBetween(first,2,4);
        while (result !=null){
            // 原顺序3215879
            System.out.print(result.val);
            result = result.next;
        }

    }

        /**
         * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
         *
         *
         * @param head ListNode类
         * @param m int整型
         * @param n int整型
         * @return ListNode类
         */
        public static SinglyListNode reverseBetween (SinglyListNode head, int m, int n) {
            SinglyListNode curTemp = new SinglyListNode(0);
            curTemp.next = head;
            head = curTemp;
            SinglyListNode nexTemp;
            SinglyListNode preTemp;

            while (n > m) {
                curTemp = head;

                for (int i = 0; i < m - 1; i++) {
                    curTemp = curTemp.next;
                }
                preTemp = curTemp;
                curTemp = curTemp.next;
                nexTemp = curTemp.next;
                for (int i = 0; i < n - m; i++) {
                    preTemp.next = nexTemp;
                    curTemp.next = nexTemp.next;
                    nexTemp.next = curTemp;
                    preTemp = preTemp.next;
                    nexTemp = curTemp.next;
                }
                n--;
            }
            return head.next;
        }


}
